package com.lank.gateway.config.service.impl;

import com.lank.boot.result.enums.SystemEnum;
import com.lank.boot.result.exception.SystemException;
import com.lank.gateway.enums.GatewayBusinessEnum;
import com.lank.gateway.enums.GatewaySystemEnum;
import com.lank.gateway.exception.GatewayBusinessException;
import com.lank.gateway.exception.GatewaySystemException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.server.resource.InvalidBearerTokenException;
import org.springframework.security.web.server.ServerAuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author 郑海宾
 * @since 2020/7/24 下午4:11 星期五
 */
@Component
@Slf4j
public class CustomAuthenticationEntryPoint implements ServerAuthenticationEntryPoint {
    @Override
    public Mono<Void> commence(ServerWebExchange exchange, AuthenticationException exception) {

        if (exception instanceof UsernameNotFoundException) {
            return Mono.error(new GatewayBusinessException(GatewayBusinessEnum.USER_NAME_NOT_FOUND));
        } else if (exception instanceof LockedException) {
            return Mono.error(new GatewayBusinessException(GatewayBusinessEnum.USER_IS_LOCKED));
        } else if (exception instanceof DisabledException) {
            return Mono.error(new GatewayBusinessException(GatewayBusinessEnum.USER_IS_DISABLED));
        } else if (exception instanceof AccountExpiredException) {
            return Mono.error(new GatewayBusinessException(GatewayBusinessEnum.USER_ACCOUNT_EXPIRED));
        } else if (exception instanceof AuthenticationCredentialsNotFoundException) {
            return Mono.error(new GatewaySystemException(GatewaySystemEnum.AUTHENTICATION_CREDENTIALS_NOT_FOUND_EXCEPTION));
        } else if (exception instanceof InvalidBearerTokenException) {
            return Mono.error(new GatewaySystemException(GatewaySystemEnum.INVALID_BEARER_TOKEN_EXCEPTION));
        } else {
            return Mono.error(new SystemException(SystemEnum.EXCEPTION.getCode(), exception.getMessage()));
        }
    }
}
